import base64
import json
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex


class PrpCrypt(object):
    def __init__(self, key, iv):
        self.key = key.encode('utf-8')
        self.mode = AES.MODE_CBC
        self.iv = iv.encode('utf-8')

    def pad_byte(self, b):
        '''
        1 先计算所传入bytes类型文本与16的余数
        2 在将此余数转成bytes 当然用0补位也可以
        3 已知了 余数 那么就用余数*被转成的余数，就得到了需要补全的bytes
        4 拼接原有文本和补位
        :param b: bytes类型的文本
        :return: 返回补全后的bytes文本
        '''
        bytes_num_to_pad = AES.block_size - (len(b) % AES.block_size)
        # python3 中默认unicode转码
        # 实际上byte_to_pad 就已经 将 数字转成了unicode 对应的字符  即使你的入参正好是16的倍数，那么bytes也是把列表整体的转码也是有值的
        # 后边解密的匿名函数 拿到最后一个数字后，就知道应该截取的长度，在反着切片就行了
        # 这样保证了数据的完整性
        byte_to_pad = bytes([bytes_num_to_pad])
        padding = byte_to_pad * bytes_num_to_pad
        padded = b + padding
        return padded

    def encrypt(self, text):
        '''
        1 先生成aes实例
        2 对传入的text转成bytes
        3 对传入的text补全
        4 调用encrypt 加密 得到密文
        5 先将密文转16进制，在将16进制用base64转码，然后在将得到的base64解码
        其实在步骤4 就已经完成了aes加密，我所在的公司加密比较复杂 ，需要的可以直接返回步骤4的值

        :param text:
        :return:
        '''
        cryptor = AES.new(self.key, self.mode, self.iv)
        text = text.encode('utf-8')
        text = self.pad_byte(text)
        self.ciphertext = cryptor.encrypt(text)
        # cryptbase64 = base64.b64encode(b2a_hex(self.ciphertext)).decode('utf8')
        # return cryptbase64
        cryptbase64 = base64.b64encode(self.ciphertext).decode('utf8')
        return cryptbase64

    def decrypt(self, text):
        '''
        解密和加密的顺序是相反的
        1 定义匿名函数，去掉补位
        2 base64解码
        3 生成aes实例
        # 4 16进制转2进制
        5 使用decrypt解码  得到补全的bytes类型明文

        :param text:
        :return:  解密且去掉补位的明文
        '''
        def unpad(s): return s[:-ord(s[len(s) - 1:])]
        base64Str = base64.b64decode(text.encode('utf8'))
        cryptor = AES.new(self.key, self.mode, self.iv)
        # aesStr = cryptor.decrypt(a2b_hex(base64Str))
        aesStr = cryptor.decrypt(base64Str).decode('utf8')
        aesStr = unpad(aesStr)
        return aesStr


if __name__ == '__main__':
    # jb1u4z5LR/c+dAb2AEKoTg==
    # ZD110036

    # data = 'liud425'
    # data = 'vv123456~'
    # pc = PrpCrypt('e2a67d5d38b881d54b48b6f57663af77', '8878254375166801')
    # redata = pc.encrypt(data)
    # print(redata)
    # result = pc.decrypt(redata)
    # print(result)

    # t='Evn1t4CZnGGVNtZzC1dZvA=='
    # print(pc.decrypt(t))

    pc = PrpCrypt('DPKlmqrMJoSePo2D59BOfzL6iJ1eQQop', '5615358033783230')
    # s = 'HwuKrmK20sn4cP8JpXp0XKWN6hdiPvhRdRkDZqBFEeaNhUGEXx5oKlFVUfZOFJWWHC89MIQs4sC1i8eCaCU3E/IPCqo9QhazjgGm3Da1x1FZA0Ffq2K5weq11BLEiwj/SeGB/JOUvFz+efqrBSuXEAgqF3nkHMimWvsxRcNrba9n2ybDfeikzpfz9+I9NXLVv6HoU47UK/YeaAn+B791jWm0h8yVprvv7GA0jK3q9J8X2kM0BdlteUzDFIN+x0kbWP7WP65aUAzfIRz6XFEjCkn6Yao4p+PnkJynZzJ3OWfD2fUKIYQmaZ1zY38G4DufASwxOjRDOldIrP1vVAlXzLNJm8/c5WetSsk+Y8hv3h3Cr0M5+onBpjQGP8WyFjv6OFFTnt/llxpLNLKrTje+SeyEUFW0LU/+bvPNZ4U70Qe3Uyq7LTqCpkwR3RAlULyFqCVRHa6LssdMl4mGep73TW0c06j8YyW2Kyica2S6IDo7lsr3Q3NP5RQFKwepwG73WtTSSRWf9JGvynLIcFsuuV94HNyMh5CQejq1xXpnkte9/nbejzFmyeYoohv6yZtJGbUaHnTaRYzsCk51LCxTSL8HmVePb6nw4GWq24z0VIcYuAWEzra8EhHPlaaQIJRxGVvrrAz5IRktDkTV1YxbfXVDq44t4UMgBXWjpLxUdWP7VbzUnCcveSbU4CKX57e0Mu3ZTFfnQVr3kibdD6eWHpPmoaFzuy5BA6sO3iDzbrSbxmMuE9Xm6SPt+Y/P+x/Tz4llKYkbTvq5Usqe5suXfzEjK4SJZtUQilwVWyHcYxQwBdY5TdbgZ3YnCQqF/9Kf5YEprD8EwtVKOT45QTNhXIFlQqa11mvQ5RClxA8YpaARznf0aUY9olead78tdnRHpEzmOlel3R9LoUM9uN+74NBLhRj6ZT9tkRUaQKRCx7IifukXDT3excxkSBe1nRAWsr9fuTyVlkPbOw1MSpGGFc/e7HILYSoyTukeyCFA6r4O5Zmv3nqKmbKuhNtzW0nu'

    # print(pc.decrypt(s))

    print('----')

    # zt = PrpCrypt('VTuNdbVaL5nwyH0dXVnTGGCWZVtDmzki','7074208132464844')
    # s2 = """7FWZYJD+V7TFa2dA10TX1jSvpilSGHRXbF8rhqxQDOcXg3nN2MNrjCBXZXAby8rkppiiIi5F/pmwKVtjmbYirVhShGW3D8qWg/+XCN8eMCYaSIV9G0jDePZjP3RXYazUzz2e9xnbOOtGhClB078rDd2Y9wQ49634qOnP4GhioKP266aC10clkBgP5oj0UQy1XVmAXtbjikzyWhhu3TQ6Kz79OgC2e132JXw7thc0dN7JLDC67aYsuXB4/ZEZUNUkLcxSw00VnSAKm7esd7xI0w78HtxRKqcQ/q1Mn6PBUsfNl9mqpxxbEhK7vkAvDJKF3KvnggzLepqh5ekqxWTAhw=="""

    # print(zt.encrypt(s2))

    # req = """
    # {
    #     "android_id": "04d4c4248cc29967",
    #     "imei": "863254010244902",
    #     "introduction": "0",
    #     "isVM": "1",
    #     "mac": "08:00:27:D0:5A:66",
    #     "pfmId": "11",
    #     "pid": "103866",
    #     "platform": "Android",
    #     "signType": "RSA",
    #     "tel": "13205776136",
    #     "timestamp": "2020-12-04 09:46:32",
    #     "unit": "VOG-AL10",
    #     "version": "1.0",
    #     "sign": "7CHIPZDDM5IfyM3ITDdS8MwmaqLpnsm2y4Z/ndi1wBeES8429arlGdUbt/fWwveDgAguV9LHZ/+PsLZYeezCqxM8IKlFNjsRwIhYX4Pw8aGo13Fp10dsqu5lrBx2yc3+OCjW8pyP/96+6B5fEQ5FgZIr064350tZ30xy6t+ck7haOSjmDJJjr0cxQWHhDSRKdQy0bVrhUA0VNPoy9lctCRiuRxIyOiNmKBuu1q5uAoNCVxEz2X0Cml4360bc6KnYylbj7yp2jqIBPy1ntWyuVVJcV12fbKTCn7WsFXbyLK2uts2I3aWZizMRuweqcuoVamPUgiTRoLeq/QyOum6PRg=="
    # }
    # """

    # ## "sign": "0XGp1K4fORp8ezteL/eSqKmNDa1kXyAKRcaIEKQlLZaAxIfmGoMs1K26odIUmJVHC4MJrgj0zdp0\ntAkIL2W5aDFx5+8iM5sh332AIr6/pUjRC5QVRVLYQ27BLU/rVUeeEYU5PNkwc1064bOLZGkX0onH\nG9pV2bi+tCfdh5PipNZcKBxrYtJaioca4PE/NW0mAarusaSe0meUl/VnCZbuDy59sdZ0Lc3YKmH0\nNG4rNqz1M5+m97Uf7wzhyaEs/SfmOXDUNil0zeQ+mSxOkBaLM/eJBM3VdwUM6KxUUUGcuUAxkL8G\nALggHhWN3O8HUM+xzq/2pg4uXIns6cgvK/ipRA\u003d\u003d\n"
    # print('aes result:' + pc.encrypt(req))

    # request = {
    #     "android_id": "04d4c4248cc29967",
    #     "idCard": "140100199401010099",
    #     "imei": "863254010244902",
    #     "introduction": "0",
    #     "isVM": "1",
    #     "mac": "08:00:27:D0:5A:66",
    #     "pid": "103866",
    #     "platform": "Android",
    #     "realName": "里杰卡尔德",
    #     "signType": "RSA",
    #     "tel": "13205776136",
    #     "timestamp": "2020-12-10 10:03:27",
    #     "unit": "VOG-AL10",
    #     "username": "ld964yxtest",
    #     "version": "1.0",
    #     "sign": "NcjfLwiNwtL299phbmAiZLFkx2DS/SyZG2g7GTWullo56P2Ex4enhC3WlXoMihIIRw5T2DLgEafLT4KqlBZxDsUHQL2/paKvQqClsDU5V1ubzizPwDd1iJgM3p84e7gHYIE36hQjPh75/Z/csLR+MDDquEjZ4hfL/EDlIGUxsskuqotE7nKIrLvyUyP+CL8KU2WT9HmlGREVvMvz/Pkkak2VmyeI/RkrFnD30K0pV7n23aMlqG26xLdQWuf700c+Vn774HPeciM2kGCiK/rZh5N8FWVLlkgTWHNkMdsBxzk5p6b3siMyyPb61kTzc5F6+gtu/t5omxBS1ZlltO5qGg=="
    # }
    request = {
          "accessToken": "QXFxUnI3eHYveWNnNDVWMkhyV2F2RzRac2ZSUTg5T3EwM1BYUnFHalBvU0JETjBNN3JGM3B6N3lWSkc4K0pWQm1tZklXZVZVTkMvOHFsdngrbkpSckhWM2R0TGwvU3R3SjV0bk4wV3VWN1E9",
          "android_id": "89b55ae86c63da6b",
          "imei": "866174491984528",
          "introduction": "V7HzWaKgyKmjwTkDZk5%2F9w%3D%3D",
          "isVM": "0",
          "loginType": "4",
          "mac": "08:00:27:2D:D8:96",
          "pid": "104725",
          "platform": "Android",
          "refreshToken": "Sm1SbGJQZzF5WDUyMkhVdUV2ZXFrcDNkK3BTTHRTS2FuOVplZS9WT0xjeTQ4aHdEK2FYRWtKMmVMN0NjT1RXNDlVRHMzVnlaRFZuY0pWdnJkT1hGUTBUVGJkMW9xbVF6SkRlRHlyYktSVjQ9",
          "signType": "RSA",
          "tel": "13815335078",
          "timestamp": "2021-04-14 10:41:46",
          "unit": "OPPO R11 Plus",
          "username": "UC191812",
          "version": "1.1",
          "sign": "Mc3Dtnr/t4Ur4PdIOPzVKEPN1ciOIhn4ujfu7ePzQgXt6yMOnxM+rZcSH8Ss78E041m0o+T9CEGC\nwS6mOKAfihW5GOYDatY9hwWVrtc7MmVAOsTiJKHRESloEiEiTboMZkuuG4DRM3LCPOqDiKQp2r9v\nAkV555IuQCHIrUrEwTTHwx/1cNkzsHjNLqZoJeHAgHNVDuAe+TEdaVFpUDKYqZZKy6iJXaXLFTu/\nf4rncgHjg+mowbp5Aww0+ZrHMeoUuxHBXwfvrqNr9ikwH1qlgW/E0m/MCP8cvBVAbV6fKrgynIyT\nssSWNBfNL+58BxHR449ElxYB1rG09TYfDoUrBg\u003d\u003d\n"
        }

    # s_req = json.dumps(request)
    # print(pc.encrypt(s_req))


    # s = '''{"android_id": "04d4c4248cc29967", "imei": "863254010244902", "introduction": "fv%2Fq2W9bqGnr3fD8oCvkxg%3D%3D", "isVM": "1", "mac": "08:00:27:D0:5A:66", "pfmId": "11", "pid": "103866", "platform": "Android", "signType": "RSA", "tel": "13205776136", "timestamp": "2020-12-16 13:50:53", "unit": "VOG-AL10", "version": "1.0", 
    # "sign": "nwZE+4xc9UE4VCFx0mXxxZrDO7vGrisCdb2kVGrH2UdtCpfLXKWJJf5OHwbyknGfWBt0N5XGyP/cp+2hTd9XpGGUc//KCaJrRzfhlYU7wZzlBXfk/WBJRwgTs27E4cC4TeF0ScbXGW3j0X8U7CdvJ9M5D2Na1lKUJY636WNaUs5aNwlM5HZU3VAgjFFwrt5Xv+qBTdGvlxRIKz+8rxb77Ij1XUJENLiY/1H5rJFL7uyxR8edhVpzaa5OWkcoIlIap2Fio+LcQKreNg+ewPUqN0c8Mb4wFJUPnufQ3pj0Eqt5BPwSTQ2bpDYoXf14v49yzo4MfPE3zjJkj1lYCwToYQ=="}'''
    # print(pc.encrypt(s))


    pc2 = PrpCrypt('amvCpadghXNnORw74LG2QdT7pwKz9kci', '8229165556696540')
    s_test = '''u7RkoXyz51cnTt++6AEGAIa3xMgiiKNTVI1yjJ8RG4dzB3kNTVkRJoSJFWllKIO7whOEZzI6HnWwdiNnbSZDfUSlNiuMtIKUdDX2QDian4aGrXJz5GZYVHWAmmBgw5gYEK5J/esdz61mao4SEzbaHfUZm/E2enov5tF8t1LApwfPQ85VKdCr2+Bc4bloFpzrE7TnbYR9LQJM6l6UGgqewLVcWwwLS+nD86DK9Kfis6PfqWQoLv7LOkz+Wfe0bx04pQ9dgaT5OnekcuQoSPOVOZ5E/JyBkqigW1KNpZnDbqgOnUlR1lixHRBt1hOW6qTBoKyW/hy++wDQo3W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